package com.game.hotSwapAgent;

import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;

import java.io.IOException;
import java.lang.management.ManagementFactory;

/**
 * @Description: 触发热更客户端
 * @Author: Mark
 * @CreateDate: 2021/12/26 16:01
 * @Copyright : 豆浆油条个人非正式工作室
 */
public class HotSwapAgentClient {

    private static final String HOT_SWAP_AGENT_JAR_PATH = "D:\\workspace\\IDEA\\Game\\lib\\hotswap\\HotSwapAgent-1.0.0.jar";

    private static final String SERVER_PI = "5964";


    public static void loadAgent() {
        loadAgent(getSelfPid());
    }

    private static void loadAgent(String pid) {
        VirtualMachine vm = null;
        try {
            vm = VirtualMachine.attach(pid);
            vm.loadAgent(HOT_SWAP_AGENT_JAR_PATH);
            System.out.println("加载agent finsh");
        } catch (AgentLoadException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AttachNotSupportedException e) {
            e.printStackTrace();
        } catch (AgentInitializationException e) {
            e.printStackTrace();
        } finally {

        }
    }

    public static String getSelfPid() {
        return ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    }
}
